<?php
/*
 * File: registration.php
 * Created: 7 июля 2007
 * Author: Andrew Dashin <dash@andrewdashin.com>
 * 
 * Description:
 *
 * Return values:
 * 
 * 0 Successfully Registred!
 * 1 Login is not defined!
 * 2 Password is not defined!
 * 3 Passwords do not match
 * 4 First name is not defined
 * 5 Last Name is not defined
 * 6 Email is not defined
 * 7 Invalid password
 * 8 Login is already in use
 * 9 Email is already in user
 */
 
if (!isset($_POST['login']) or empty($_POST['login'])) {
	echo '1';
    exit(0);
}
if (!isset($_POST['password']) or empty($_POST['password'])) {
	echo '2'; // Invalid password
    exit(0);
}
if (!isset($_POST['confirmpassword']) or empty($_POST['confirmpassword']) or
    $_POST['password'] != $_POST['confirmpassword']) {
	echo '3';
    exit(0);
}
if (!isset($_POST['firstname']) or empty($_POST['firstname'])) {
	echo '4';
    exit(0);
}
if (!isset($_POST['lastname']) or empty($_POST['lastname'])) {
	echo '5';
    exit(0);
}
if (!isset($_POST['email']) or empty($_POST['email'])) {
	echo '6'; // invalid email
    exit(0);
}
if (strlen($_POST['password']) < 5) {
    echo '7'; // Password is too weak
    exit(0);
}

$_POST['login'] = substr($_POST['login'], 0, 30);
$_POST['password'] = substr($_POST['password'], 0, 255);
$_POST['email'] = substr($_POST['email'], 0, 30);
$_POST['firstname'] = substr($_POST['firstname'], 0, 30);
$_POST['lastname'] = substr($_POST['lastname'], 0, 30);

$db = MySQL::getInstance();
if ($db->fetchAssoc(
            $db->sql("SELECT * FROM `users` WHERE `login` = ':0'")->bind($_POST['login'])
            )) {
    echo '8'; // User with such login already exist
    exit(0);
}

if ($db->fetchAssoc(
            $db->sql("SELECT * FROM `users` WHERE `email` = ':0'")->bind($_POST['email'])
            )) {
    echo '9'; // User with such email already exist
    exit(0);
}

$confirmationCode = mt_rand(999999, 99999999);

$db->sql("INSERT INTO `users` SET " .
"               `login`             = ':0'," .
"               `password`          = password(':1')," .
"               `email`             = ':2'," .
"               `first_name`        = ':3'," .
"               `last_name`         = ':4',".
"               `confirmation_code` = ':5'")->bind( $_POST['login'],
                                                $_POST['password'],
                                                $_POST['email'],
                                                $_POST['firstname'],
                                                $_POST['lastname'],
                                                $confirmationCode);

if (mail($_POST['email'],
    "MyWebEr Registration confirmation",
    "To confirm your registration please follow {URL}index.php?action=confirmation&confirmationcode={$confirmationCode}",
    "From: donotreply@andrewdashin.com\r\nContent-type: text/plain; UTF-8\r\n")) {
    echo "0";
} else {
    echo "10";
}

?>
